#===============================================================================
# Koro Business Environment
# Copyright (C) 2008  Antonio Corroppoli
#
#This file is part of Koro BE.
# 
# Koro BE is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Koro BE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Koro BE; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#===============================================================================

'''
Created on 09/ago/2011

@author: antstud
'''

import wx
from koro import util
from koro.core import exception
from koro.ui.wxgui.pages import BasePage,TablePage
from koro.ui.wxgui.widgets import controls as co,dialogs
from koro.ui.wxgui.mellcfg import mDefaultBorder
from koro.modules.prodotti.ui import panel
        

#===============================================================================
# ProdottiPage
#===============================================================================
class ProdottiPage(BasePage):
    TITLE='Prodotti'
    def __init__(self,*args,**kwargs):
        BasePage.__init__(self,*args,**kwargs)                
        self.__do_layout(args[2])        
        self.__bind()        
        self.SetAutoLayout(True)
        #self.init_page_view()
                       
    def __do_layout(self,objects):
        #mainsizer=self.Sizer
        fieldsizer = wx.GridBagSizer(0,0)
        self.notebook=co.KoroNotebook(self)
        
        self.set_list_columns(co.Column('ID',80,'get_ID_fmt'),
                              co.Column('Descrizione',350,'descrizione'),
                              co.Column('Fornitore',150,'get_fornitore_principale_fmt'),
                              )
        self.load_list_objects(objects)
#        self.list_manager.load(objects)
#        if not objects:
#            self.enable_page(False)
                    
        #vsizer.Add(boxsizer,0)
        #fnbstyle=fnb.FNB_NODRAG|fnb.FNB_NO_X_BUTTON|fnb.FNB_NO_NAV_BUTTONS|fnb.FNB_FANCY_TABS
        #self.notebook.SetInitialSize((450,100))
        self.prodotto_panel=panel.ProdottoPanel(self)
        self.notebook.SetInitialSize((535,-1))
        self.notebook.AddPage(self.prodotto_panel, "Prodotto", True)
        #self.notebook.AddPage(wx.Panel(self), "Immagine", False)
        #self.notebook.AddPage(wx.Panel(self), "Magazzino", False)
        #self.notebook.AddPage(wx.Panel(self), "Note", False)
        #vsizer.Add(self.notebook,1,flag=wx.ALL|wx.EXPAND,border=0)
        
        fieldsizer.Add(self.notebook,(0,0),flag=wx.ALL|wx.EXPAND ,border=0)#riga zero colonna 1
        fieldsizer.Add(self.list_manager.get_managed_list(),(0,1),flag=wx.ALL|wx.EXPAND ,border=0)#riga zero colonna 1        
        fieldsizer.AddGrowableRow(0)
        fieldsizer.AddGrowableCol(1)
        
        self.Sizer.Add(fieldsizer,1,flag=wx.ALL|wx.EXPAND ,border=5)#riga zero colonna 1
        
        self.Sizer.Layout()
    
    def __bind(self):
        self.prodotto_panel.Bind(panel.EVT_FORNITORE_EDIT,self._fornitore_edit_handler)
        self.prodotto_panel.Bind(panel.EVT_FORNITORE_ADD,self._fornitore_add_handler)
        self.prodotto_panel.Bind(panel.EVT_FORNITORE_REMOVE,self._fornitore_rem_handler)
        self.prodotto_panel.Bind(panel.EVT_PREZZO_EDIT, self._prezzo_edit_handler)
    
    def _fornitore_edit_handler(self,evt):
        self.edit_info_fornitore(evt.info_fornitore)
    
    def _fornitore_add_handler(self,evt):
        obj=self.list_manager.get_selected_object()
        try:
            info_fornitore=obj.add_info_fornitore(evt.fornitore)
            if not self.edit_info_fornitore(info_fornitore):
                obj.remove_info_fornitore(info_fornitore)
        except exception.KoroDuplicatedObject,msg:
            wx.GetApp().show_error(msg)
    
    def _fornitore_rem_handler(self,evt):
        obj=self.list_manager.get_selected_object()
        obj.remove_info_fornitore(evt.info_fornitore)
        self.update_fields(obj)
    
    def _prezzo_edit_handler(self,evt):
        prezzo_prodotto=evt.prezzo_prodotto
        dlg=dialogs.KoroDialog(self,
                               header='Prezzo Prodotto',
                               subheader='Prodotto {0}:{1}'.format(evt.prezzo_prodotto.prodotto.ID,
                                                                   evt.prezzo_prodotto.prodotto.descrizione.replace(util.newlinechar(),' ')),
                               size=(420,310),
                               toolbar=True)
        dlg.set_panel(panel.PrezzoPanel(dlg))
        dlg.update(prezzo_prodotto)
        self._show_prezzo_dialog(dlg,prezzo_prodotto)
        wx.EVT_CHAR_HOOK            
    
    def _show_prezzo_dialog(self,dlg,prezzo_prodotto):
        action=dlg.show()
        if action==wx.ID_ABORT:
            dlg.Destroy()
            return
        try:
            dlg.update_object(prezzo_prodotto)
            dlg.Destroy()
            obj=self.list_manager.get_selected_object()
            self.update_object(obj)
            self.update_fields(obj)
        except Exception, e:
            wx.GetApp().show_error(e)
            self._show_prezzo_dialog(dlg,prezzo_prodotto)
        
    def edit_info_fornitore(self,info_fornitore):
        dlg=dialogs.KoroDialog(self,
                               header='Info Fornitore',
                               subheader='Fornitore:{0}'.format(info_fornitore.get_fornitore_fmt()),
                               size=(450,250),
                               toolbar=True)
        dlg.set_panel(panel.InfoFornitorePanel(dlg))
        dlg.update(info_fornitore)
        action=dlg.show()
        if action==wx.ID_ABORT:
            dlg.Destroy()
            return False
        try:
            dlg.update_object(info_fornitore)
        except exception.KoroDuplicatedObject,msg:
            wx.GetApp().show_error(msg)
            dlg.Destroy()
            return False
        obj=self.list_manager.get_selected_object()
        self.update_object(obj)
        if info_fornitore.principale:            
            obj.set_fornitore_principale(info_fornitore.fornitore)
        self.update_fields(obj)
        return True
            
    
    def enable_page(self,enable=True):
        self.notebook.Enable(enable)
    
    def update_fields(self,obj):
        print 'ProdottiPage.update_fields'
        self.Freeze()
        self.prodotto_panel.update_fields(obj)
        self.Thaw()
    
    def reset_fields(self):
        print 'ProdottiPage.reset_fields'
        self.prodotto_panel.reset_fields()
    
    def reset_focus(self):
        self.prodotto_panel.reset_focus()
    
    def update_object(self,obj):
        print 'ProdottiPage.update_object'
        self.prodotto_panel.update_object(obj)
    
    def after_delete(self):
        self.update()
    
#    def _request_categorie_prodotti(self):
#        observer=wx.GetApp().get_observer()
#        observer.set_context('CATEG_PRODOTTI')
#        return observer.get_objects()
#    
#    def fill_combobox(self):
#        #combobox fornitori
#        #self.fornitore.load(self._request_fornitori())        
#        #combobox categorie prodotti
#        self.categoria.load(self._request_categorie_prodotti())


#class ProdottiPage_old(BasePage):
#    TITLE='Prodotti'
#    def __init__(self,*args,**kwargs):
#        BasePage.__init__(self,*args,**kwargs)                
#        self.__do_layout(args[2])
#        #self.on_page_focus()
#        #self.list_ctrl.load(self._objects_list)
#        self.__bind()
#        #self.list_ctrl.select(0,True)
#        self.SetAutoLayout(True)
#        self.init_page_view()        
#    
#    def __do_layout(self,objects):
#        mainsizer=self.Sizer
#        fieldsizer = wx.GridBagSizer(0,0)
#        vsizer=wx.BoxSizer(wx.VERTICAL)
#        #lborder = 10
#        #tborder = 6
#        boxsizer=wx.BoxSizer(wx.VERTICAL)
#        
#        self.ID = co.mTextCtrl(id=wx.NewId(),parent=self,size=(55,-1),mstyle=co.mTE_READ_ONLY)#co.mTE_REQUIRED|co.mTE_DIGIT_ONLY|co.mTE_ZFILL)
#        boxsizer.Add(co.CompositeCtrl(self.ID,label='ID'),0,wx.ALL,border=mDefaultBorder)
#
#        self.codice = co.mTextCtrl(id=wx.NewId(), parent=self, size=wx.Size(200, -1),mstyle=co.mTE_UPPER|co.mTE_REQUIRED)
#        boxsizer.Add(co.CompositeCtrl(self.codice,label='Codice Forn.'),0,wx.ALL,border=mDefaultBorder)
#
#        self.descrizione = co.mTextCtrl(id=wx.NewId(),parent=self,size=wx.Size(250, -1),mstyle=co.mTE_TITLED)
#        boxsizer.Add(co.CompositeCtrl(self.descrizione,label='Descrzione'),0,wx.ALL,border=mDefaultBorder)
#
#        self.fornitore = co.ComboBox(id=wx.NewId(),parent=self,size=wx.Size(250, 25),style=wx.CB_READONLY,item_info='ragione_sociale')
#        boxsizer.Add(co.CompositeCtrl(self.fornitore,label='Fornitore'),0,wx.ALL,border=mDefaultBorder)
#        
#        self.categoria = co.ComboBox(id=wx.NewId(),parent=self,size=wx.Size(250, 25),style=wx.CB_READONLY,item_info='nome')
#        boxsizer.Add(co.CompositeCtrl(self.categoria,label='Categoria'),0,wx.ALL,border=mDefaultBorder)
#        
#        self.list_manager.set_columns(columns_info=(co.Column('ID',50,'get_ID_fmt'),
#                                                    co.Column('Codice',120,'codice'),
#                                                    co.Column('Descrizione',400,'descrizione'),
#                                                    co.Column('Fornitore',200,('fornitore','ragione_sociale')),
#                                                    ))
#        self.list_manager.load(objects)
#        if not objects:
#            self.enable_page(False)
#                    
#        vsizer.Add(boxsizer,0)
#        #fnbstyle=fnb.FNB_NODRAG|fnb.FNB_NO_X_BUTTON|fnb.FNB_NO_NAV_BUTTONS|fnb.FNB_FANCY_TABS
#        self.notebook=co.KoroNotebook(self)
#        #self.notebook.SetInitialSize((450,100))
#        self.listini=panel.PrezziProdottoPanel(self)
#        self.notebook.AddPage(self.listini, "Prezzi", True)
#        #self.notebook.AddPage(wx.Panel(self), "Immagine", False)
#        self.notebook.AddPage(wx.Panel(self), "Magazzino", False)
#        self.notebook.AddPage(wx.Panel(self), "Note", False)
#        vsizer.Add(self.notebook,1,flag=wx.ALL|wx.EXPAND,border=4)
#        
#        fieldsizer.Add(vsizer,(0,0),flag=wx.ALL|wx.EXPAND ,border=0)#riga zero colonna 1
#        fieldsizer.Add(self.list_manager.get_managed_list(),(0,1),flag=wx.ALL|wx.EXPAND ,border=1)#riga zero colonna 1        
#        fieldsizer.AddGrowableRow(0)
#        fieldsizer.AddGrowableCol(1)
#        
#        mainsizer.Add(fieldsizer,1,flag=wx.ALL|wx.EXPAND ,border=10)#riga zero colonna 1
#        
#        mainsizer.Layout()
#        
#    def __bind(self):
#        pass
##        self.Bind(wx.EVT_LIST_ITEM_SELECTED,self._Selected)
###        #self.Bind(wx.EVT_LIST_ITEM_FOCUSED,self._Focused)
###        #self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,self._Activated)
#
#    def update_fields(self,dataObj):
#        print 'ProdottiPage.update_fields'
#        #i=dataObj.getIndirizzo()
#        self.ID.SetValue(dataObj.get_ID_fmt())
#        self.codice.SetValue(dataObj.codice)
#        self.descrizione.SetValue(dataObj.descrizione)
#        self.fornitore.set_value(dataObj.fornitore.ragione_sociale)
#        self.categoria.set_value(dataObj.categoria.nome)
#        #observer=wx.GetApp().get_observer()
#        #observer.set_prezzi_prodotto_context()
#        #prezzi=observer.get_objects(prodotto=dataObj)
#        self.listini.update_fields(dataObj)
#    
#    def reset_fields(self):
#        print 'ProdottiPage.reset_fields'
#        self.ID.Clear()
#        self.codice.Clear()
#        self.descrizione.Clear()
#        self.fornitore.set_value("")
#        self.categoria.set_value("")
#        self.listini.reset_fields()
#    
#    def reset_focus(self):
#        self.codice.SetFocus()
#    
#    def update_object(self,obj):
#        print 'ProdottiPage.update_object sistemare'
#        obj.set_ID(self.ID.GetValue())
#        obj.codice=self.codice.GetValue()
#        obj.descrizione=self.descrizione.GetValue()
#        obj.fornitore= self.fornitore.get_selected_object()
#        obj.categoria= self.categoria.get_selected_object()
#        self.listini.update_object(obj)
#
##    def after_save(self):
##        self.update()
#    
#    def after_delete(self):
#        self.update()
#    
#    def on_page_focus(self):
#        print "ProdottiPage.on_page_focus"
#        self.fill_combobox()
##        obj=self.GetCurrentObject()
##        if obj is not None:
##            self.listini.update_fields(obj)
#    
#    def _request_fornitori(self):
#        observer=wx.GetApp().get_observer()
#        observer.set_context('FORNITORI')
#        return observer.get_objects()
#    
#    def _request_categorie_prodotti(self):
#        observer=wx.GetApp().get_observer()
#        observer.set_context('CATEG_PRODOTTI')
#        return observer.get_objects()
#    
#    def fill_combobox(self):
#        #combobox fornitori
#        self.fornitore.load(self._request_fornitori())        
#        #combobox categorie prodotti
#        self.categoria.load(self._request_categorie_prodotti())
        

#PAGE_DEFAULT_STYLE=wx.NO_BORDER|wx.CLIP_CHILDREN|wx.TAB_TRAVERSAL
#class CategorieProdottiPage(wx.Panel):
#    TITLE='Categorie Prodotti'
#    def __init__(self,parent,context,objects_list,style=PAGE_DEFAULT_STYLE,toolbar=True,*args,**kwargs):
#        wx.Panel.__init__(self,parent,style=style,*args,**kwargs)
#        self.Reparent(wx.GetApp().get_main_frame())
#        self._panel=CategorieProdottiPagePanel(parent,context,objects_list,*args,**kwargs)
#    
#    def show_table(self):
#        self.dlg=dialogs.KoroDialog(self,title=self.TITLE,size=(600,400),style=wx.THICK_FRAME)
#        self.dlg.set_panel(self._panel)#esegue reparent
#        self.dlg.show(False)
#        #self.Show(False)
#        #self.Reparent(dlg.Parent)
#        #dlg.Destroy()
#    
#    def before_close(self):
#        self._panel.before_close()
#        self.dlg.Close()
#        self.dlg.Destroy()

class CategorieProdottiPage(TablePage):
    TITLE='Categorie Prodotti'
    def __init__(self,*args,**kwargs):
        TablePage.__init__(self,*args,**kwargs)
        #self._set_dialog_size((600,420))
        #self._set_dialog_size((600,420))
    
    def _get_panel(self,*args,**kwargs):
        return CategorieProdottiPagePanel(*args,**kwargs)
        
        

#===============================================================================
# CategorieProdottiPage
#===============================================================================
class CategorieProdottiPagePanel(BasePage):
    TITLE='Categorie Prodotti'
    def __init__(self,*args,**kwargs):
        BasePage.__init__(self,*args,**kwargs)                
        
        self.nome = co.LabelTextCtrl(self,label='Nome',maxlen=50,size=(300, -1),mstyle=co.mTE_TITLED|co.mTE_REQUIRED,orientation=wx.VERTICAL)
        self.add_subcateg_btn=wx.Button(self,label='Aggiungi',style=wx.NO_BORDER)
        self.rem_subcateg_btn=wx.Button(self,label='Rimuovi',style=wx.NO_BORDER)
        self.subcateg_list_manager=co.KoroListCtrlManager()
        self.subcateg_list_manager.set_managed_list(co.KoroListCtrl(self,edit=True,size=(-1,235)))
        
        self.__do_layout(args[2])
        #self.list_ctrl.load(self._objects_list)
        #self.fill_combobox()#per ora non c'e' la gestione delle sottocategorie
        self.__bind()
        #self.list_ctrl.select(0,True)
        self.SetAutoLayout(True)
        #self.Layout()
        #self.init_page_view()
    
    def show(self):
        pass        
    
    def __do_layout(self,objects):
        self.fieldsizer = fieldsizer = wx.GridBagSizer(0,0)
        boxsizer=wx.BoxSizer(wx.VERTICAL)
        hsizer=wx.BoxSizer()
        
        boxsizer.Add(self.nome,0,wx.ALL,border=mDefaultBorder)
        
        hsizer.Add(self.add_subcateg_btn,0)
        hsizer.Add(wx.StaticLine(self,style=wx.LI_VERTICAL),0,wx.EXPAND|wx.LEFT|wx.RIGHT,border=1)
        hsizer.Add(self.rem_subcateg_btn,0)
        boxsizer.Add(hsizer,0,wx.TOP,border=20)
        
        self.subcateg_list_manager.set_columns(columns_info=(co.Column('Sottocategorie',200,'nome'),))
        boxsizer.Add(self.subcateg_list_manager.get_managed_list(),0,wx.EXPAND|wx.ALL,border=1)
        
        fieldsizer.Add(boxsizer,(0,0),flag=wx.ALL|wx.EXPAND ,border=0)
        
        self.list_manager.set_list_size((300,200))
        self.set_list_columns(co.Column('Categorie',200,'nome'))        
        self.load_list_objects(objects)
        
        fieldsizer.Add(self.list_manager.get_managed_list(),(0,1),flag=wx.ALL|wx.EXPAND,border=1)
        fieldsizer.AddGrowableCol(1)
        fieldsizer.AddGrowableRow(0)
        self.Sizer.Add(fieldsizer,1,flag=wx.ALL|wx.EXPAND ,border=10)#riga zero colonna 1 
        #mainsizer.Layout()
    
    def __bind(self):
        self.subcateg_list_manager.get_managed_list().Bind(wx.EVT_LIST_END_LABEL_EDIT,
                                                          self._subcateg_edit_handler)
        self.add_subcateg_btn.Bind(wx.EVT_BUTTON,self._subcateg_add_handler)
        self.rem_subcateg_btn.Bind(wx.EVT_BUTTON, self._subcateg_rem_handler)
    
    def enable_page(self,enable=True):
        self.list_manager.enable_list(enable)
        self.subcateg_list_manager.enable_list(enable)
        self.nome.enable(enable)
        self.add_subcateg_btn.Enable(enable)
        self.rem_subcateg_btn.Enable(enable)
    
    def _subcateg_edit_handler(self,evt):
        subcateg=self.subcateg_list_manager.get_selected_object()
        subcateg.nome=evt.GetLabel()
    
    def _subcateg_add_handler(self,evt):
        categ=self.list_manager.get_selected_object()
        if categ is None:
            return
        subcateg=categ.add_sottocategoria()
        observer=wx.GetApp().get_observer()
        observer.set_context('CATEG_PRODOTTI')
        observer.add_sottocategoria(subcateg)
        self.subcateg_list_manager.load(categ.sottocategorie)
    
    def _subcateg_rem_handler(self,evt):
        categ=self.list_manager.get_selected_object()
        if categ is None:
            return
        subcateg=self.subcateg_list_manager.get_selected_object()
        if subcateg is None:
            wx.GetApp().show_message('Seleziona la sottogategoria da eliminare.')
            return
        categ.remove_sottocategoria(subcateg)
        observer=wx.GetApp().get_observer()
        observer.set_context('CATEG_PRODOTTI')
        observer.remove_sottocategoria(subcateg)
        self.subcateg_list_manager.load(categ.sottocategorie)

    def update_fields(self,obj):
        print 'CategorieProdottiPage.update_fields'
        #self.ID.SetValue(str(obj.ID))
        self.nome.set_value(obj.nome)
        self.subcateg_list_manager.load(obj.sottocategorie)

    def update_object(self,obj):
        print 'CategorieProdottiPage.update_object'
        #obj.set_ID(self.ID.GetValue())
        obj.nome=self.nome.get_value()
    
    def reset_fields(self):
        print 'CategorieProdottiPanel.reset_fields'
        #self.ID.Clear()
        self.nome.clear()
        
    def reset_focus(self):
        self.nome.set_focus()

    def after_delete(self):
        self.update()
